package com.cpi.cornpp.costelement.services;

import java.util.ArrayList;
import java.util.Collection;

import com.cpi.cornpp.costelement.dao.CostElementDAO;
import com.cpi.cornpp.costelement.dto.CostElementDTO;
import com.cpi.cornpp.costelement.exception.CostElementException;

public class CachedCostElementList{

	private static Collection list = new ArrayList(0);
	
	private static CachedCostElementList instance;
	
	private CachedCostElementList(){
		init();
	}	
	
	private static CachedCostElementList getInstance(){
		if(instance == null){
			instance = new  CachedCostElementList(); 
		}
		return instance;
	}
	
	private void init(){
		CostElementDAO costElementDAO = new CostElementDAO();
		try {
			list = costElementDAO.getList();	
		} catch (CostElementException e) {
			e.printStackTrace(System.out);
		}
	}
	
	public static void addCostElement(CostElementDTO c){
		list.add(c);
	}
	
	public static void updateCostElement(CostElementDTO c){
		CostElementDTO ceView = null;
		ArrayList values = null;
		if(list.contains(c)){
			values = (ArrayList)list;
			ceView = (CostElementDTO)values.get(values.indexOf(c));
			ceView.setCostElementCode(c.getCostElementCode());
			ceView.setCostElementDescription(c.getCostElementDescription());
		}
	}
	
	private static Collection getList(){
		return list;
	}
	
	public static CostElementDTO getItem(int costElementId){
		CachedCostElementList.getInstance();
		ArrayList values = (ArrayList)CachedCostElementList.getList();
		return (CostElementDTO)values.get(costElementId);
	}

	public static void removeItem(CostElementDTO costElementDTO){
		if(list.contains(costElementDTO))
			list.remove(costElementDTO);
	}
	
}
